package com.immoc.demo.service.impl;

import com.immoc.demo.dao.AreaDao;
import com.immoc.demo.entity.Area;
import com.immoc.demo.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author zzy
 * @Description service层的实现，需要注意事务的相关配置
 * @Date 2018/4/7 16:50
 * @Version 1.0
 **/
@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaDao areaDao;

    @Override
    public List<Area> getAreaList() {

        return areaDao.queryArea();
    }

    @Override
    public Area getAreaById(int areaId) {
        int i = 1/0;
        return areaDao.queryAreaById(areaId);
    }
    //注意此处要加上事务管理
    @Override
    @Transactional
    public boolean addArea(Area area) {
        if(!StringUtils.isEmpty(area.getAreaName())&& !StringUtils.isEmpty(area.getPriority())){
            area.setCreateTime(new Date());
            area.setLastEditTime(new Date());
            try {

                Integer effectNum = areaDao.insertArea(area);
                if(effectNum ==1){
                    return true;
                }else {
                    throw new RuntimeException("添加区域失败");
                }
            } catch (RuntimeException e) {
                throw new RuntimeException("添加区域失败"+e.getMessage());
            }
        }else {
            throw new RuntimeException("添加区域参数不能为空");
        }

    }

    @Override
    @Transactional()
    public boolean modifyArea(Area area) {
        if(!StringUtils.isEmpty(area.getAreaId())){
            area.setLastEditTime(new Date());
            try {
                Integer effectNum = areaDao.updateArea(area);
                if(effectNum ==1){
                    return true;
                }else {
                    throw new RuntimeException("修改区域失败");
                }
            } catch (RuntimeException e) {
                throw new RuntimeException("修改区域失败"+e.getMessage());
            }
        }else {
            throw new RuntimeException("修改区域参数不能为空");
        }
    }

    @Override
    public boolean deleteByAreaId(int areaId) {
        if(!StringUtils.isEmpty(areaId)){
            try {
                Integer effectNum = areaDao.deleteAreaById(areaId);
                if(effectNum ==1){
                    return true;
                }else {
                    throw new RuntimeException("删除区域失败");
                }
            } catch (RuntimeException e) {
                throw new RuntimeException("删除区域失败"+e.getMessage());
            }
        }else {
            throw new RuntimeException("删除区域失败参数不能为空");
        }
    }
}
